import { observable, action, autorun, toJS } from 'mobx';
import _ from 'lodash';
import { WeaForm } from 'comsMobx';
import * as API from '../../apis/card';
import { message, Modal } from 'antd';
import { ReplyAddStore } from './add';
import window, { MyWindow } from '../../util';
import { WeaLocaleProvider,WeaTools } from 'ecCom';
import IndexAPI from '../../apis';
import jQuery from "jquery";
const getParent = WeaTools.WindowFunc.getParent;
const getLabel = WeaLocaleProvider.getLabel;

export default class ReplyStore {
  @observable iconInfo = {
    icon: "icon-coms-ModelingEngine",
    iconColor: "#fff",
    iconBg: "#96358a"
  }

  constructor(props?: any) {
    if (props) {
      this.init(props);
    }
    autorun(() => {
      window.changeLoadingState && window.changeLoadingState(this.loading);
      if (getParent().location.href.indexOf('/main/cube/card') > -1) {
        const parentWindow: MyWindow = getParent() as MyWindow;
        parentWindow.changeLoadingState && parentWindow.changeLoadingState(this.loading);
      }
    });
  }

  @action
  init = (props: any = {}) => {
    this.update(props);
    this.conditionInfo = [{
      colSpan: 2,
      conditionType: 'INPUT',
      domkey: [
        'content'
      ],
      fieldcol: 12,
      isQuickSearch: true,
      label: getLabel(131393, '内容'),
      labelcol: 6,
      value: '',
      viewAttr: 2
    }, {
      browserConditionParam: {
        completeParams: {},
        conditionDataParams: {},
        dataParams: {},
        destDataParams: {},
        hasAddBtn: false,
        hasAdvanceSerach: true,
        idSeparator: ',',
        isAutoComplete: 1,
        isDetail: 0,
        isMultCheckbox: false,
        isSingle: true,
        linkUrl: '/hrm/resource/HrmResource.jsp?id=',
        pageSize: 10,
        quickSearchName: '',
        replaceDatas: [],
        title: getLabel(172, '选择') + getLabel(26225, '发表人'),
        type: '1',
        viewAttr: 2
      },
      colSpan: 2,
      conditionType: 'BROWSER',
      domkey: [
        'operatorid'
      ],
      fieldcol: 12,
      isQuickSearch: false,
      label: getLabel(26225, '发表人'),
      labelcol: 6,
      viewAttr: 2
    }, {
      colSpan: 2,
      fieldcol: 12,
      labelcol: 6,
      conditionType: 'DATE',
      datas: [
        {name: getLabel(332, '全部'), value: '0'},
        {name: getLabel(15537, '今天'), value: '1'},
        {name: getLabel(15539, '本周'), value: '2'},
        {name: getLabel(15541, '本月'), value: '3'},
        {name: getLabel(21904, '本季'), value: '4'},
        {name: getLabel(15384, '本年'), value: '5'},
        {name: getLabel(27347, '上个月'), value: '7'},
        {name: getLabel(81716, '上一年'), value: '8'},
        {name: getLabel(32530, '指定日期范围'), value: '6'}  // 时间范围的值必须为6
      ],
      domkey:
        ['createdateselect', 'createdatefrom', 'createdateto'],
      label: getLabel(21663, '操作日期'),
      value: '',
      viewAttr: 2,
    }, {
      colSpan: 2,
      conditionType: 'WeaInput',
      rules: 'integer|min:1',
      domkey: [
        'floorNum'
      ],
      fieldcol: 12,
      isQuickSearch: true,
      label: getLabel(27519, '楼号'),
      labelcol: 6,
      value: '',
      viewAttr: 2,
    }];
    this.condition = new WeaForm();
    this.condition.initFormFields([{items: this.conditionInfo}]);
    this.replyAdd.initReplyAddStore({
      ..._.pick(this.modeInfo, ['maincategory', 'subcategory', 'seccategory']),
      contentid: `field${this.replyModeInfo.replayContentFieldId}`,
      callSubmit: this.submitReply,
      isdefault:this.isdefault,
      showbuttons:this.showbuttons
    })
    this.loading = false;

  }

  conditionInfo: any[];
  @observable condition: any;
  @observable searchContent = '';

  @observable showReply:any = void(0);
  @observable replyposition: any = "1";
  @observable scrollTop: Number = 0;


  @observable replyModeInfo: any = {};
  @observable modeInfo: any = {};
  @observable replyList: any[] = [];
  @observable dateList: any[] = [];
  @observable replyData: any = {};
  @observable scrollBottom: any = {};
  @observable getScrollTop: any = {};


  @observable pagesize: number = 5;
  @observable total: number = 0;
  @observable pagecount: number = 0;
  @observable current: number = 1;

  @observable loading: boolean = false;

  @observable isdefault: boolean = true;
  @observable showbuttons:any = {};

  @observable replyAdd: ReplyAddStore = new ReplyAddStore();

  @observable params: any = {};

  modeId: string;
  billid: string;
  formId: string;

  @observable tabDatas: { key: string, title: string | JSX.Element | JSX.Element[] }[] = [
    {title: getLabel('332', '全部'), key: '1'},
    {title: getLabel(32572, '与我相关'), key: '2'}
  ]
  @observable selectedKey: string = '1';

  @observable showSearchDrop: boolean = false;
  @observable showRichText:boolean = false;
  @action
  initReply = () => {
    this.loading = true;
    this.params.pagesize = this.pagesize;
    this.params.current = this.current;
    IndexAPI.getAppInfoByID({modeid:this.params.modeId}).then((data:any)=>{
      if (data.status == "1") {
          this.iconInfo = {
            icon:data.icon || "icon-coms-ModelingEngine",
            iconColor: data.iconColor ||"#fff",
            iconBg: data.iconBg || "#96358a"
          };
        }
  });
    API.initReply(this.params).then(({status, errorCode, error, ...props}) => {
      if (status == '1') {
        this.update(this.params);
        this.init(props);
      } else {
        message.error(`[${getLabel(127353, '错误') + errorCode}]:${error}`);
        //   throw api_errormsg;
      }
      this.loading = false;
    })
  }

  @action
  update = (param: any) => {
    for (let key in param) {
      _.set(this, key, _.get(param, key));
    }
  }
  @action
  updateParams = (params: any) => {
    let temp = false;
    if (!_.isEqual(toJS(this.params), params)) {
      temp = true;
    }
    this.params = params
    if (temp) {
      this.initReply();
    }
  }
  @action
  reloadSearch = (params: any) => {
    this.params = params
    this.initReply();
  }
  @action
  changeTab = (key: string) => {
    this.selectedKey = key;
    this.search({replySearchtype: key});
  }
  quickSearch = (e) => {
    const keyCode = e.charCode || e.keyCode;
    if (keyCode == 13) {
      if (this.condition.has('content')) {
        this.condition.$('content').set('value', e.target.value);
      }
      this.doSearch({content: e.target.value})
    }
  }
  @action
  showSearch = () => {
    this.showSearchDrop = true;
  }
  @action
  hideSearch = () => {
    this.showSearchDrop = false;
  }
  @action
  doSearch = (params) => {
    this.loading = true;
    this.hideSearch();
    const _params: any = {
      pagesize: this.pagesize,
      current: params.current?params.current:1,
      modeId: this.modeId,
      formId: this.formId,
      billid: this.billid, ...params,
      replySearchtype: this.selectedKey,
      replyposition:this.replyposition,
    };

    API.reply(_params).then(({status, errorCode, error, ...props}) => {
      if (status == '1') {
        if(this.replyAdd.okClickType!='new'&&this.replyAdd.okClickType!='quote'){//不等于新建或者引用
            if (typeof(this.getScrollTop) === 'function') {
              this.scrollTop = this.getScrollTop();
            }
        }
        this.update(props);
        if (typeof(this.scrollBottom) === 'function') {
          this.scrollBottom();
        }
      } else {
        message.error(`[${getLabel(127353, '错误') + errorCode}]:${error}`);
        //   throw api_errormsg;
      }
      this.loading = false;
    })
  }

  @action
  onPageChange = (current = this.current, pageSize = this.pagesize) => {
    this.current = current;
    this.pagesize = pageSize;
    this.search({replySearchtype: this.selectedKey == '2' ? '2' : ''}, {current, pagesize: pageSize});
  }

  search = (__, params = this.params) => {
    const _params: any = {}
    const values: any = this.condition.values();
    for (let key in values) {
      const keys = key.split('__');
      keys.forEach((k, index) => {
        _.set(_params, k, _.get(values, `${key}${keys.length > 1 ? '[' + index + ']' : ''}`) || '')
      })
    }
    let p = {...params, ..._params};
    if(__.current){
       p.current = __.current;
    }
    this.searchContent = this.condition.values().content?this.condition.values().content:"";
    this.doSearch(p);
  }

  @action
  resetSearch = () => {
    jQuery(".ant-input").val("");
    this.condition.resetConditionValue();
  }

  @action
  add = () => {
    this.replyAdd.visible = true;
    this.replyAdd.popup=false;
    this.replyAdd.initContent({}, 'new');
  }

  @action
  edit = (replyData) => {
    this.replyAdd.visible = true;
    this.replyAdd.initContent(replyData, 'edit');
  }

  @action
  deleteItem =(id)=>{
    for(let i=0;i<this.replyList.length;i++){//删除这一个选项即可
      if(this.replyList[i].id==id){
        this.replyList.splice(i,1);
        break;
      }
    }
  }

  @action
  delete = (replyData) => {
    this.loading = true;
    let id  =_.get(replyData, 'id');
    API.deleteReply({
      id: id, modeId: this.modeId, billid: this.billid, formId: this.formId
    }).then(({status, errorCode, error, message: msg, messageType}) => {
      if (status == '1') {
        if (messageType == '1') {
          message.success(msg);
          if (this.current == 1) {//第一页
            if (this.pagecount == 1) {//仅一页
              this.deleteItem(id);
            } else if (this.replyList.length < 5) {//大于1页且当前少于5项目
              this.search({ replySearchtype: this.selectedKey == '2' ? '2' : '' })
            } else {
              this.deleteItem(id);
            }
          } else if (this.current == this.pagecount) {//最后一页
            this.deleteItem(id);
          } else {
            this.search({ replySearchtype: this.selectedKey == '2' ? '2' : '' })
          }
        } else {
          message.error(msg);

        }

        this.replyAdd.initContent({}, 'new');//重新初始化为新建
      } else {
        message.error(`[${getLabel(127353, '错误') + errorCode}]:${error}`);
      }
      this.loading = false;
    })
  }


  @action
  like = (replyData) => {
    this.loading = true;
    let id =  _.get(replyData, 'id');
    API.likeReply({
      id:id,
      modeId: this.modeId,
      billid: this.billid,
      formId: this.formId,
      current: this.current,
      pagesize: this.pagesize
    }).then(({api_status, api_errormsg,item}) => {
      if (api_status) {
        this.setReplyItem(item);
        //this.search({replySearchtype: this.selectedKey == '2' ? '2' : ''})
      } else {
        if (api_errormsg) {
          Modal.warning({
            content: api_errormsg
          })
        }
        // throw api_errormsg;
      }
      this.loading = false;
    })
  }

  @action
  unlike = (replyData) => {
    this.loading = true;
    let id =  _.get(replyData, 'id');
    API.unlikeReply({
      id: id,
      modeId: this.modeId,
      billid: this.billid,
      formId: this.formId,
      current: this.current,
      pagesize: this.pagesize
    }).then(({api_status, api_errormsg,item}) => {
      if (api_status) {
        this.setReplyItem(item);
        //this.search({replySearchtype: this.selectedKey == '2' ? '2' : ''})
      } else {
        if (api_errormsg) {
          Modal.warning({
            content: api_errormsg
          })
        }
        // throw api_errormsg;
      }
      this.loading = false;
    })
  }

  @action
  reference = (replyData, offset, flag) => {
    // this.replyAdd.visible = true;
    // this.replyAdd.initContent(replyData, 'quote');
    this.replyAdd.isInitPopup = true;
    this.replyAdd.popup = true;
    this.replyAdd.initContent(replyData, 'quote');
    this.replyAdd.popupOffset = offset;
    this.replyAdd.popupArrowPostion = !!flag;
  }

  @action
  referenceRight = (replyData) => {
    this.replyAdd.isInitPopup = true;
    this.replyAdd.popup = true;
    this.replyAdd.initContent(replyData, 'quote');
  }

  @action
  about = (replyData, offset, flag) => {
    this.replyAdd.isInitPopup = true;
    this.replyAdd.popup = true;
    this.replyAdd.initContent(replyData, 'comment');
    this.replyAdd.popupOffset = offset;
    this.replyAdd.popupArrowPostion = !!flag;
  }

  @action
  aboutRight = (replyData) => {
    this.replyAdd.isInitPopup = true;
    this.replyAdd.popup = true;
    this.replyAdd.initContent(replyData, 'comment');
  }


  @action
  loadNextPage = () => {
    this.current = this.current+1;
    this.replyposition = 2;
    this.scrollTop = this.getScrollTop();
    this.onPageChange();
  }

  setReplyItem=(item)=>{
    for(let i=0;i<this.replyList.length;i++){//编辑时只要替换这一个选项即可
      if(this.replyList[i].id==item.id){
        this.replyList[i] = item;
        break;
      }
    }
  }
  @action
  submitReply = (params) => {
    let content =  params.replycontent.replace(/\u200B/g,'');
    let index = content.indexOf("#@split@#</span></p>");
    if(index!=-1){
      content = content.substring(index+"#@split@#</span></p>".length);
    }
    let tempcontent = content;
    if(tempcontent!==""){
      tempcontent=tempcontent.replace("&nbsp;","");
      tempcontent=tempcontent.replace("\n","");
    }
    if (tempcontent.trim() === ''||tempcontent=="<p></p>") {
      message.error(`${getLabel(33285, ' 评论的内容不能为空')}`);
      this.replyAdd.loading = false;
      this.replyAdd.popup = false;
      return;
    }else{
      //提交时，去掉光标特殊字符：&#8203;，否零宽字符会变成问号
      let Base64 = WeaTools.Base64;
      content = Base64.encode(content);
      params.replycontent = content;
    }


    this.loading = true;
    const _params: any = {
      reqModeId: this.modeId,
      reqBillid: this.billid,
      reqFormid: this.formId,
      from: 'reply',
      src: 'submit',
      isFormMode: '1',
      layoutid: this.replyModeInfo.layoutid,
      formId: this.replyModeInfo.formid,
      modeId: this.replyModeInfo.id,
      current: this.current,
      pagesize: this.pagesize,
    };
    API.replySubmit({..._params, ...params}).then(({status, errorCode, error, message: msg, messageType,item}) => {
      if (status == '1') {
        if (messageType == '0') {
          Modal.error({
            content: msg
          });
        }else{
          if(item&&item.id&&item.id>0){
              this.setReplyItem(item);
          }
          this.search({replySearchtype: this.selectedKey == '2' ? '2' : '',current : this.current})
        }

        this.replyAdd.visible = false;
      } else {
        message.error(`[${getLabel(127353, '错误') + errorCode}]:${error}`);
        //  throw api_errormsg;
      }
      this.replyAdd.initContent({}, 'new');//重新初始化为新建
      this.loading = false;
      this.replyAdd.loading = false;
      this.replyAdd.popup = false;
    });
  }

  @action
  isShowAddReplyText=(bool)=>{
    this.showRichText = bool;
  }
}
